package utils.dbutils;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * Created by guo on 2017/11/11.
 */
public class C3P0utils {
    public static DataSource ds=null;
    public static ThreadLocal<Connection> th=new ThreadLocal<Connection>();
    static {
        ds=new ComboPooledDataSource();
    }
    public static DataSource getDs()
    {
        return ds;
    }

    public static Connection getConnection() throws SQLException {
        Connection conn=th.get();
        if(conn!=null)
        {
            return conn;//带事物连接
        }
        return ds.getConnection();//此连接不带事物
    }
    public static void startTransaction() throws SQLException {
        Connection conn=th.get();
        if(conn!=null)
        {
            throw new RuntimeException("事物已开启，不需要再开启");
        }
        conn=ds.getConnection();
        conn.setAutoCommit(false);
        th.set(conn);
    }
    public static void commitTransaction() throws SQLException {
        Connection conn=th.get();
        if(conn!=null)
        {
            throw new RuntimeException("本身没有事物，无法提交");
        }
        conn.commit();
        conn.close();
        conn=null;
        th.remove();
    }
    public static void closeTransaction(Connection connection) throws SQLException {
       Connection conn=th.get();
       if(conn!=connection)///只关闭普通连接，带事物的连接在提交或回滚的时候关闭
       {
           connection.close();
       }
    }
}
